package com.example.demo.leetcode.classics150;

import java.util.LinkedList;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _35螺旋矩阵
 * @description
 * @date 2023/07/19 17:04
 * <p>
 * ******************************************************
 */
public class _35螺旋矩阵 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        List<Integer> result = new LinkedList<>();

        int upper_bound = 0;
        int down_bound = m - 1;
        int left_bound = 0;
        int right_bound = n - 1;

        while (result.size() < n * m) {

            // 上
            if (result.size() < n * m && upper_bound <= down_bound) {
                for (int i = left_bound; i <= right_bound; i++) {
                    result.add(matrix[upper_bound][i]);
                }
                upper_bound++;
            }

            // 右
            if (result.size() < n * m && left_bound <= right_bound) {
                for (int i = upper_bound; i <= down_bound; i++) {
                    result.add(matrix[i][right_bound]);
                }
                right_bound--;
            }

            // 下
            if (result.size() < n * m && upper_bound <= down_bound) {
                for (int i = right_bound; i >= left_bound; i--) {
                    result.add(matrix[down_bound][i]);
                }
                down_bound--;
            }

            // 左
            if (result.size() < n * m && left_bound <= right_bound) {
                for (int i = down_bound; i >= upper_bound; i--) {
                    result.add(matrix[i][left_bound]);
                }
                left_bound++;
            }

        }

        return result;
    }
}
